package com.ktwlsoft.archivemanage.domain.business.businessService.businessInspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.businessService.BasisBusinessManageService;
import com.ktwlsoft.archivemanage.domain.business.businessService.ImgUploadService;
import com.ktwlsoft.archivemanage.domain.business.businessService.MendListService;
import com.ktwlsoft.archivemanage.domain.business.businessService.NotifyMessageScheduleTask;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.BusinessInspectRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.InspectSubjectItemRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.InspectSubjectRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.mend.MendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.BasisBusinessManage;
import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.BusinessInspect;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.InspectSubject;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.InspectSubjectItem;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendList;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendSubject;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendSubjectOption;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessInspect.*;
import com.ktwlsoft.archivemanage.payload.guiBusiness.BasisBusinessManageRequest;
import com.ktwlsoft.archivemanage.payload.guiBusiness.CommitRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 业务检查
 *
 * @author zhuhe on 2019/11/12 15:20
 * @version 1.0
 */
@Component
public class BusinessInspectService {

    /**
     * 业务检查
     */
    private final BusinessInspectRepositoryService repositoryService;

    /**
     * 业务检查题目
     */
    private final InspectSubjectRepositoryService subjectRepositoryService;

    /**
     * 业务检查题目选项
     */
    private final InspectSubjectItemRepositoryService itemRepositoryService;

    /**
     * 图片
     */
    private final ImgsService imgsService;

    /**
     * 整改单
     */
    private final MendListService mendListService;

    /**
     * 整改单
     */
    private final MendListRepositoryService mendListRepositoryService;

    private final NotifyMessageScheduleTask notifyMessageScheduleTask;

    /**依据*/
    private final BasisBusinessManageService basisBusinessManageService;

    private final AccountRepositoryService accountRepositoryService;

    public BusinessInspectService(BusinessInspectRepositoryService repositoryService, InspectSubjectRepositoryService subjectRepositoryService, InspectSubjectItemRepositoryService itemRepositoryService, ImgsService imgsService, MendListService mendListService, MendListRepositoryService mendListRepositoryService, NotifyMessageScheduleTask notifyMessageScheduleTask, BasisBusinessManageService basisBusinessManageService, AccountRepositoryService accountRepositoryService) {
        this.repositoryService = repositoryService;
        this.subjectRepositoryService = subjectRepositoryService;
        this.itemRepositoryService = itemRepositoryService;
        this.imgsService = imgsService;
        this.mendListService = mendListService;
        this.mendListRepositoryService = mendListRepositoryService;
        this.notifyMessageScheduleTask = notifyMessageScheduleTask;
        this.basisBusinessManageService = basisBusinessManageService;
        this.accountRepositoryService = accountRepositoryService;
    }

    /**
     * 业务检查新增 on 2019/11/6 16:55
     *
     * @param request request
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(BusinessInspectSaveRequest request) {
        List<BusinessInspect> guidances = repositoryService.getByGuidanceNum(request.getGuidanceNum());
        if (guidances != null && guidances.size() > 0) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("检查单号重复");
        }
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            account = new Account();
        }
        BusinessInspect businessInspect = new BusinessInspect();
        BeanUtils.copyProperties(request, businessInspect);
        if (request.getInstructorSignImg() != null) {
            businessInspect.setInstructorSign(String.valueOf(imgsService.save(businessInspect.getId(), "UNITADVICE", request.getInstructorSignImg().getUrl())));
        } else {
            businessInspect.setInstructorSign("");
        }
        if (request.getUnitSignImg() != null) {
            businessInspect.setUnitSign(String.valueOf(imgsService.save(businessInspect.getId(), "UNITSIGN", request.getUnitSignImg().getUrl())));
        } else {
            businessInspect.setUnitSign("");
        }
        if(ObjectUtil.isEmpty(businessInspect.getState())){
            businessInspect.setState(BusinessInspect.state.STAGE);
        }
        businessInspect.setCreator(account.getRealName());
        businessInspect.setCreatorId(account.getId());
        businessInspect.setUpdate(account.getRealName());
        businessInspect.setUpdateId(account.getId());
        businessInspect.setRecycle(0);
        //题目
        List<InspectSubject> subjectList = Lists.newArrayList();
        //选项
        List<InspectSubjectItem> itemList = Lists.newArrayList();
        //依据
        List<BasisBusinessManage> manageList = Lists.newArrayList();
        //题目
        if (request.getSubjectSaveRequests() != null && request.getSubjectSaveRequests().size() > 0) {
            request.getSubjectSaveRequests().forEach(value -> {
                InspectSubject subject = new InspectSubject();
                BeanUtils.copyProperties(value, subject);
                subject.setInspectId(businessInspect.getId());
                subject.setCreatorId(businessInspect.getCreatorId());
                subject.setCreator(businessInspect.getCreator());
                subjectList.add(subject);
                //选项
                if (value.getItemList() != null && value.getItemList().size() > 0) {
                    value.getItemList().forEach(itemValue -> {
                        InspectSubjectItem item = new InspectSubjectItem();
                        BeanUtils.copyProperties(itemValue, item);
                        item.setSubjectId(subject.getId());
                        item.setCreatorId(subject.getCreatorId());
                        item.setCreator(subject.getCreator());
                        itemList.add(item);
                        if (itemValue.getImgsList() != null && itemValue.getImgsList().size() > 0) {
                            imgsService.manySave(item.getId(), "ITEMIMGS", itemValue.getImgsList());
                        }
                    });
                }
                if (value.getImgsList() != null && value.getImgsList().size() > 0) {
                    imgsService.manySave(subject.getId(), "HASIMGS", value.getImgsList());
                }
                //依据
                if(value.getBasisBusinessManages() != null){
                    for(BasisBusinessManageRequest basis:value.getBasisBusinessManages()){
                        basis.setId(SnowFlake.getNextId());
                        basis.setBusinessId(subject.getId());
                        basis.setBasisType("default");
                        basis.setCreateId(businessInspect.getCreatorId());
                        basis.setCreateName(businessInspect.getCreator());
                        basis.setCreateTime(new Date());
                        BasisBusinessManage manage = BasisBusinessManage.builder().build();
                        BeanUtils.copyProperties(basis,manage);
                        try {
                            manage.setContent(basis.getContent().getBytes("UTF-8"));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        manageList.add(manage);
                    }
                }
            });
        }
        try {
            repositoryService.insert(businessInspect);
            if (subjectList.size() > 0) {
                subjectRepositoryService.manyInsert(subjectList);
            }
            if (itemList.size() > 0) {
                itemRepositoryService.manyInsert(itemList);
            }
            if(manageList.size() > 0){
                basisBusinessManageService.getRepositoryService().manyInsert(manageList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException(ResultType.SAVING_ERROR.getReason(),ResultType.SAVING_ERROR);
        }
        return Result.ok(businessInspect.getId());
    }

    /**
     * 业务检查修改 on 2019/11/12 17:54
     *
     * @param request request
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> modify(BusinessInspectUpdateRequest request) {
        List<BusinessInspect> guidances = repositoryService.getByGuidanceNum(request.getGuidanceNum());
        if (guidances != null && guidances.size() > 0) {
            for (BusinessInspect guidance : guidances) {
                if (!guidance.getId().equals(request.getId())) {
                    return Result.body(null, ResultType.CHECK_ERROR).withMessage("指导单号重复");
                }
            }
        }
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            account = new Account();
        }
        BusinessInspect businessInspect = new BusinessInspect();
        BeanUtils.copyProperties(request, businessInspect);
        if (request.getInstructorSignImg() != null) {
            if (request.getInstructorSignImg().getType().equals(1)) {
                businessInspect.setInstructorSign(String.valueOf(imgsService.save(businessInspect.getId(), "UNITADVICE", request.getInstructorSignImg().getUrl())));
            }
            if (request.getInstructorSignImg().getType().equals(2)) {
                ImgUploadService.deleteById(request.getInstructorSignImg().getId());
            }
        }
        if (request.getUnitSignImg() != null) {
            if (request.getUnitSignImg().getType().equals(1)) {
                businessInspect.setUnitSign(String.valueOf(imgsService.save(businessInspect.getId(), "UNITSIGN", request.getUnitSignImg().getUrl())));
            }
            if (request.getUnitSignImg().getType().equals(2)) {
                ImgUploadService.deleteById(request.getUnitSignImg().getId());
            }
        }
        businessInspect.setUpdate(account.getRealName());
        businessInspect.setUpdateId(account.getId());
        businessInspect.setRecycle(null);
        List<InspectSubject> subjectList = Lists.newArrayList();
        List<InspectSubjectItem> itemList = Lists.newArrayList();
        if (request.getSubjectSaveRequests() != null && request.getSubjectSaveRequests().size() > 0) {
            for(GuidanceSubjectUpdateRequest value:request.getSubjectSaveRequests()){
                InspectSubject subject = new InspectSubject();
                BeanUtils.copyProperties(value, subject);
                subjectList.add(subject);
                if (value.getImgsList() != null && value.getImgsList().size() > 0) {
                    ImgUploadService.handleImg(subject.getId(), "HASIMGS", value.getImgsList());
                }
                //处理依据
                try {
                    basisBusinessManageService.handleBasis(value.getBasisBusinessManages(),value.getId(),account,"default");
                }catch (Exception e){
                    e.printStackTrace();
                    throw new ResultException("处理依据报错");
                }
                if (value.getItemList() != null && value.getItemList().size() > 0) {
                    value.getItemList().forEach(itemValue -> {
                        InspectSubjectItem item = new InspectSubjectItem();
                        BeanUtils.copyProperties(itemValue, item);
                        itemList.add(item);
                        if (itemValue.getImgsList() != null && itemValue.getImgsList().size() > 0) {
                            ImgUploadService.handleImg(item.getId(), "ITEMIMGS", itemValue.getImgsList());
                        }
                    });
                }
            }
        }
        try {
            repositoryService.update(businessInspect);
            if (subjectList.size() > 0) {
                for (InspectSubject subject : subjectList) {
                    subjectRepositoryService.update(subject);
                }
            }
            if (itemList.size() > 0) {
                for (InspectSubjectItem item : itemList) {
                    itemRepositoryService.update(item);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException(ResultType.UPDATE_ERROR.getReason(),ResultType.UPDATE_ERROR);
        }
        return Result.ok(businessInspect.getId());
    }

    /**
     * 提交 on 2020/5/7 16:56
     *
     * @param commitRequest commitRequest
     * @return Result<?>
     */
    public Result<?> commit(CommitRequest commitRequest){
        if (commitRequest.getId() == null) {
            return Result.body(commitRequest.getId(), ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspect inspect = repositoryService.getById(commitRequest.getId());
        if (inspect == null) {
            return Result.body(commitRequest.getId(), ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if(!BusinessInspect.state.STAGE.equals(inspect.getState())){
            return Result.body(inspect.getState(), ResultType.CHECK_ERROR).withMessage("只有暂存状态可以提交");
        }
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        inspect.setUpdate(account.getRealName());
        inspect.setUpdateId(account.getId());
        inspect.setUpdateAt(new Date());
        inspect.setState(BusinessInspect.state.WAIT_CONFIRM);
        try {
            notifyMessageScheduleTask.businessGuideAddNotifyMessage(inspect,commitRequest.getCopyTos());
            repositoryService.update(inspect);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(commitRequest.getId(), ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(commitRequest.getId());
    }

    /**
     * 业务检查撤销 on 2019/11/13 10:45
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> revokeById(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspect businessInspect = repositoryService.getById(id);
        if (businessInspect == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        MendList mendList1 = mendListRepositoryService.getByInspectId(businessInspect.getId());
        if (mendList1 != null) {
            if (!mendList1.getMendState().equals(MendList.MendState.WAIT_MEND)) {
                return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不可撤销,因为整改单状态不是待整改");
            }
        }
        businessInspect.setState(BusinessInspect.state.STAGE);
        MendList mendList = mendListRepositoryService.getByInspectId(businessInspect.getId());
        if (mendList != null) {
            mendListService.deleteMend(mendList.getId());
        }
        //删除检查员签字
        if(businessInspect.getInstructorSign() != null && !"".equals(businessInspect.getInstructorSign())) {
            ImgUploadService.deleteById(Long.valueOf(businessInspect.getInstructorSign()));
        }
        //删除被检查单位签字
        if(businessInspect.getUnitSign() != null && !"".equals(businessInspect.getUnitSign())) {
            ImgUploadService.deleteById(Long.valueOf(businessInspect.getUnitSign()));
        }
        businessInspect.setInstructorSign("");
        businessInspect.setUnitSign("");
        try {
            repositoryService.update(businessInspect);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(id, ResultType.UPDATE_ERROR);
        }
        return Result.ok(businessInspect.getGuidanceNum());
    }

    /**
     * 业务检查删除 on 2019/11/13 16:22
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> deleteById(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspect businessInspect = repositoryService.getById(id);
        if (businessInspect == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            account = new Account();
        }
        businessInspect.setRecycle(1);
        businessInspect.setCreatedAt(null);
        businessInspect.setRecycleTime(new Date());
        businessInspect.setUpdate(account.getRealName());
        businessInspect.setUpdateId(account.getId());
        try {
            repositoryService.update(businessInspect);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(id, ResultType.UPDATE_ERROR);
        }
        return Result.ok(businessInspect.getGuidanceNum());
    }

    /**
     * 业务检查下达整改单 on 2019/11/13 11:03
     *
     * @param id id
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> releaseMendList(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspect businessInspect = repositoryService.getById(id);
        if (businessInspect == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        MendList mendList = new MendList();
        //模板id
        mendList.setTemId(businessInspect.getTemId());
        //业务检查外键
        mendList.setInspectId(businessInspect.getId());
        //模板名称
        mendList.setTemName(businessInspect.getTemName());
        //指导单号
        mendList.setGuidNum(businessInspect.getGuidanceNum());
        //立档单位
        mendList.setArchiveUnit(businessInspect.getUnitName());
        //指导员
        mendList.setInstructor(businessInspect.getCreator());
        //指导员id
        mendList.setInstructorId(businessInspect.getCreatorId());
        //指导员签字
        mendList.setInstructorSign(businessInspect.getInstructorSign());
        //考核地理位置
        mendList.setGpsAddress(businessInspect.getGpsAddress());
        //档案员
        mendList.setArchivist(businessInspect.getArchivist());
        //档案员id
        mendList.setArchivistId(businessInspect.getArchivistId());
        //档案员电话
        mendList.setArchivistPhone(businessInspect.getArchivistPhone());
        //被指导单位签字
        mendList.setUnitSign(businessInspect.getUnitSign());
        //被指导单位签字时间
        mendList.setUnitSignDate(businessInspect.getUpdateAt());
        //满分
        mendList.setFullMark(businessInspect.getFullMark());
        //得分
        mendList.setMark(businessInspect.getMark());
        //指导意见
        mendList.setGuidAdvice(businessInspect.getGuidAdvice());
        //被指导意见
        mendList.setUnitAdvice(businessInspect.getUnitAdvice());
        //单位地址
        mendList.setUnitAddress(businessInspect.getUnitAddress());
        // 创建时间
        mendList.setCreatedAt(new Date());
        // 创建人
        mendList.setCreator(businessInspect.getCreator());
        // 创建人Id
        mendList.setCreatorId(businessInspect.getCreatorId());
        //题目子级
        List<InspectSubject> subjectList = subjectRepositoryService.getByInspectId(businessInspect.getId());
        List<InspectSubjectItem> itemList = itemRepositoryService.findList(null);
        if (subjectList != null && subjectList.size() > 0) {
            List<MendSubject> mendSubjects = Lists.newArrayList();
            subjectList.forEach(value -> {
                MendSubject mendSubject = new MendSubject();
                BeanUtils.copyProperties(value, mendSubject);
                mendSubject.setMendId(mendList.getId());
                mendSubject.setGuidanceSubjectId(value.getId());
                mendSubject.setGroupName(value.getGroup());
                mendSubject.setHasImgs(value.getHasImgs());
                mendSubject.setMust(value.getMust());
                mendSubject.setSort(value.getSort());
                mendSubject.setMultiOption(value.getMultiOption());
                mendSubject.setAdditionSubstraction(Byte.valueOf(String.valueOf(value.getAdditonOrSubstraction())));
                mendSubject.setCustom(value.getIsCustom());
                mendSubjects.add(mendSubject);
                //题目项目
                if (itemList != null && itemList.size() > 0) {
                    List<MendSubjectOption> optionList = Lists.newArrayList();
                    itemList.forEach(itemValue -> {
                        if (itemValue.getSubjectId().equals(value.getId())) {
                            MendSubjectOption option = new MendSubjectOption();
                            option.setId(itemValue.getId());
                            option.setSubjectId(mendSubject.getId());
                            option.setOptionName(itemValue.getOption());
                            option.setOptionMark(itemValue.getOptionMark());
                            option.setSort(itemValue.getSort());
                            option.setChecked(itemValue.getChecked());
                            option.setHasImgs(itemValue.getHasImgs());
                            optionList.add(option);
                        }
                    });
                    mendSubject.setSubjectOptionList(optionList);
                }
            });
            mendList.setSubjects(mendSubjects);
        }
        try {
            mendListService.insertMendList(mendList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(id, ResultType.SAVING_ERROR);
        }
        return Result.ok(id);
    }

    /**
     * 业务检查列表 on 2019/11/13 11:32
     *
     * @param request request
     * @return Result<?>
     */
    public Result<?> findPage(BusinessInspectFindPageRequest request, String type) {
        Account account = UserPrincipal.getCurrentUser();
        JSONObject object = new JSONObject();
        object.put("temId", request.getTemId() != null ? request.getTemId() : null);
        if ("wx".equals(type)) {
            object.put("userId", account != null ? account.getId() : null);
        } else if ("pc".equals(type)) {
            if(account != null && !"ADMIN".equals(account.getRoleName()) && !"管理员".equals(account.getRoleName())
                    && !"业务指导处长".equals(account.getRoleName()) && !"正副局长".equals(account.getRoleName())){
                object.put("manageUserId", account.getId());
            }
        }
        object.put("type", type);
        object.put("state", request.getState() != null ? request.getState() : null);
        object.put("instructorId", request.getInstructorId() != null ? request.getInstructorId() : null);
        object.put("guidanceTimeStart", request.getGuidanceTimeStart() != null ? DateUtils.dayMinTime(request.getGuidanceTimeStart()) : null);
        object.put("guidanceTimeEnd", request.getGuidanceTimeEnd() != null ? DateUtils.dayMaxTime(request.getGuidanceTimeEnd()) : null);
        object.put("markStart", request.getMarkStart() != null ? request.getMarkStart() : null);
        object.put("markEnd", request.getMarkEnd() != null ? request.getMarkEnd() : null);
        object.put("keyWords", request.getKeyWords() != null ? request.getKeyWords() : null);
        object.put("field", request.getField() != null ? request.getField().replaceAll("[A-Z]", "_$0").toLowerCase() : null);
        object.put("order", request.getOrder() != null ? request.getOrder().equals(BusinessInspectFindPageRequest.order.ascend) ? "ASC" : "DESC" : null);
        object.put("inspectType", request.getInspectType() != null ? request.getInspectType(): "default");
        if (request.getPn() == null) {
            request.setPn(1);
        }
        if (request.getPageSize() == null) {
            request.setPageSize(30);
        }
        PageInfo<BusinessInspect> pageInfo = repositoryService.findPage(request.getPn(), request.getPageSize(), object);
        return Result.ok(pageInfo);
    }

    /*指导人列表*/
    public Result<?> FindInstructors() {
        return Result.ok(repositoryService.findInstructors());
    }

    /**
     * 获取业务检查详情 on 2019/11/13 11:56
     *
     * @param id id
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> getById(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspect businessInspect = repositoryService.getById(id);
        if (businessInspect == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        //保留为null的字段
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(businessInspect, SerializerFeature.WriteMapNullValue));
        //指导员签字图片
        Imgs instructorSignImg = new Imgs();
        instructorSignImg.setBusinessId(businessInspect.getId());
        instructorSignImg.setBusinessType("UNITADVICE");
        jsonObject.put("instructorSignImg", imgsService.getByBusinessIdAndBusinessType(instructorSignImg));
        //被指导单位签字图片
        Imgs unitSignImg = new Imgs();
        unitSignImg.setBusinessId(businessInspect.getId());
        unitSignImg.setBusinessType("UNITSIGN");
        jsonObject.put("unitSignImg", imgsService.getByBusinessIdAndBusinessType(unitSignImg));
        //获取题目
        List<InspectSubject> subjectList = subjectRepositoryService.getByInspectId(businessInspect.getId());
        List<Imgs> imgss = imgsService.findList(null);
        List<InspectSubjectItem> itemList = itemRepositoryService.findList(null);
        List<JSONObject> list = Lists.newArrayList();
        if (subjectList != null && subjectList.size() > 0) {
            for (InspectSubject subject : subjectList) {
                JSONObject subjectJson = JSONObject.parseObject(JSON.toJSONString(subject, SerializerFeature.WriteMapNullValue));
                //获取选项
                List<JSONObject> items = Lists.newArrayList();
                if (itemList != null && itemList.size() > 0) {
                    itemList.forEach(value -> {
                        if (value.getSubjectId().equals(subject.getId())) {
                            JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(value, SerializerFeature.WriteMapNullValue));
                            itemJson.put("imgsList", getHandelImg(imgss, value.getId(), "ITEMIMGS"));
                            items.add(itemJson);
                        }
                    });
                }
                //获取题目图片
                subjectJson.put("imgsList", getHandelImg(imgss, subject.getId(), "HASIMGS"));
                subjectJson.put("itemList", items);
                //依据
                List<BasisBusinessManageRequest> requestList = Lists.newArrayList();
                List<BasisBusinessManage> manageList = basisBusinessManageService.getRepositoryService().findList(BasisBusinessManage.builder().businessId(subject.getId()).basisType("default").build());
                if(manageList != null){
                    manageList.forEach(basisValue->{
                        BasisBusinessManageRequest request = new BasisBusinessManageRequest();
                        BeanUtils.copyProperties(basisValue,request);
                        try {
                            request.setContent(new String(basisValue.getContent(),"UTF-8"));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        requestList.add(request);
                    });
                }
                subjectJson.put("basisBusinessManages",requestList);
                list.add(subjectJson);
            }
        }
        jsonObject.put("subjects", list);
        //指导员电话
        String updatePhone = "";
        if(businessInspect.getUpdateId() != null) {
            Account account = accountRepositoryService.getById(businessInspect.getUpdateId());
            if(account != null){
                updatePhone = account.getTeleNum();
            }
        }
        jsonObject.put("updatePhone",updatePhone);
        return Result.ok(jsonObject);
    }

    /**
     * 获取年度所有指导单号
     *
     * @param createdAtFrom
     * @param createdAtTo
     * @return
     */
    public Result<?> getGuidNumsByYear(String createdAtFrom, String createdAtTo) {
        return Result.ok(repositoryService.getGuidNumsByYear(createdAtFrom, createdAtTo));
    }

    /**
     * 获取处理后的图片 on 2020/3/12 11:21
     *
     * @param imgss 图片集合
     * @param bId   业务id
     * @param bType 业务类型
     * @return List<Imgs>
     */
    private List<Imgs> getHandelImg(List<Imgs> imgss, Long bId, String bType) {
        List<Imgs> imgss1 = Lists.newArrayList();
        if (imgss != null && imgss.size() > 0) {
            imgss.forEach(value -> {
                if (value.getBusinessId().equals(bId) && (bType).equals(value.getBusinessType())) {
                    imgss1.add(value);
                }
            });
        }
        return imgss1;
    }

    /**
     * @Description 获取当前指导人已上报条数
     * @params:
     * @returns:
     * @dateTime:
     */
    public Result<?> getRecorderMount(Long userId) {
        int result = 0;
        String regEx = "[^0-9]";
        String count = repositoryService.getRecorderMount(userId);
        Pattern p = Pattern.compile(regEx);
        if (count != null) {
            Matcher m = p.matcher(count);
            result = Integer.parseInt(m.replaceAll("").trim());
        }
        return Result.ok(result);
    }

    /**
     * 立档单位确认
     *
     * @param request UnitConfirmRequest
     * @return Result<?>
     */
    public Result<?> unitConfirm(InspectConfirmRequest request){
        if (request.getId() == null) {
            return Result.body(request.getId(), ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspect businessInspect = repositoryService.getById(request.getId());
        if (businessInspect == null) {
            return Result.body(request.getId(), ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if(!BusinessInspect.state.WAIT_CONFIRM.equals(businessInspect.getState())){
            return Result.body(businessInspect.getState(), ResultType.CHECK_ERROR).withMessage("只有待确认状态可以进行该操作");
        }
        if (request.getUnitSignImg() != null) {
            businessInspect.setUnitSign(String.valueOf(imgsService.save(businessInspect.getId(), "UNITSIGN", request.getUnitSignImg().getUrl())));
        }
        businessInspect.setUnitAdvice(request.getUnitAdvice());
        businessInspect.setState(BusinessInspect.state.COMPLETE);
        try {
            repositoryService.update(businessInspect);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request.getId(), ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(request.getId());
    }
}